package com.example.secondassignment;


import java.util.List;

import android.os.Bundle;
import android.preference.PreferenceManager;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.inputmethodservice.Keyboard.Row;
import android.view.ContextMenu;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.ContextMenu.ContextMenuInfo;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;

public class MyCountries extends Activity {
		
	private Activity main_activity;
    
    private ListView listView;
    private MyAdapter adapter;
    private List<CountryVisited> countryVisits;

    private CountryVisitedDataSource datasource;
    
    private boolean updateFlag=false;
    
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.mycountries_activity);
		
		System.out.println("onCreate");
		
		main_activity = this; // Create variable for this activity. Makes it easier to handle intents
	
		setUpdb();	// Create and starts the database.
		
		//setUpListView();
       
		//addCountriesFromdb(); //Adds all countryVisits from the database to the listView
        setUpActionBar();	// Creates an actionbar     
       
        
	}
    
	@Override
    protected void onResume() {
		super.onResume();
		System.out.println("onResume!!!");
		
		datasource.open();
		setUpListView();
		addCountriesFromdb();
		
      
    }

    @Override
    protected void onPause() {
      datasource.close();
      super.onPause();
    }
    
    private void setUpListView(){
    	
    	listView = (ListView)findViewById(R.id.countryList);
    	
    	registerForContextMenu(listView);
    	
    	adapter = new MyAdapter(this,R.layout.mycountries_list_item);
    	
    }
      	
    private void setPreferences(TextView wantedView){
    	String backgroundcolor, textcolor;
    	int fontsize = 20;
    	
    	SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
    	
    	backgroundcolor = prefs.getString("BackgroundColor", "Black");
    	textcolor = prefs.getString("TextColor", "White");
    	//fontsize = prefs.getInt("FontSize", 20);
	    try{
	    	fontsize = Integer.parseInt(prefs.getString("Fontsize", "20"));
	    }
	    catch(Exception e){ /* DO NOTHING */ }
    	
	    wantedView.setBackgroundColor(getColor(backgroundcolor));
	    wantedView.setTextColor(getColor(textcolor));
	    wantedView.setTextSize(fontsize);

    }
      
    private int getColor(String colorTxt){
    	int color = 0;
    	if(colorTxt.compareTo("Black") == 0){ color = Color.BLACK; }
    	if(colorTxt.compareTo("White") == 0){ color = Color.WHITE; }
    	if(colorTxt.compareTo("Red") == 0){ color = Color.RED; }
    	if(colorTxt.compareTo("Green") == 0){ color = Color.GREEN; }
    	if(colorTxt.compareTo("Blue") == 0){ color = Color.BLUE; }
    
    	return color;
    }
    
    private void sortBy(String sortBy){
    	
		for( CountryVisited countryVisited : countryVisits ){
	   		adapter.remove(countryVisited);
	   		//datasource.deleteCountryVisited(countryVisited);
		}
		countryVisits.clear();
    	countryVisits = datasource.getAllCountryVisitsSortedBy(sortBy);
    	
		for( CountryVisited countryVisited : countryVisits ){
			adapter.add(countryVisited);
			//listView.setAdapter(adapter);
		}
    	adapter.notifyDataSetChanged();
    }
    
    private void addVisitedCountry(int year, String country){
	   CountryVisited countryVisited = datasource.createCountryVisited(year,country); // Save result in database and create a CountryVisited.
	   countryVisits.add(countryVisited);
	   
	   adapter.add(new String(countryVisited.toString()));
	   listView.setAdapter(adapter);
   }
    
   	private void updateVisitedCountry(int year, String country, int position ){	
   		CountryVisited countryVisited = countryVisits.get(position);
   		
   		String yearTxt = year+"";
   		System.out.println("Year: "+year+" Country: "+country);
   		
   		datasource.updateCountryVisited(countryVisited.getId(), yearTxt, country);
   		countryVisited.setCountry(country);
   		countryVisited.setYear(year);
   		
   		adapter.notifyDataSetChanged();
   	}

    private void addCountriesFromdb(){
		
    	SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
    	
		countryVisits = datasource.getAllCountryVisits();
		for( CountryVisited countryVisited : countryVisits ){
			adapter.add(countryVisited);
		}
		listView.setAdapter(adapter);
		adapter.notifyDataSetChanged();
		
		sortBy(prefs.getString("SortOrder", ""));
				
	}
	
    private void setUpdb(){
		datasource = new CountryVisitedDataSource(this);
		datasource.open();		
	}
	    
	private void setUpActionBar(){
		getActionBar();
	}
		
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.action_menu_mycountries, menu);
		
		return true;
	}

	@Override
    public boolean onOptionsItemSelected(MenuItem item) { 
		SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
		SharedPreferences.Editor edit = prefs.edit();		
    	switch (item.getItemId()) {
        case R.id.add_country:  	
        	/* Start new Activity AddCountryVisited */
        	Intent intent = new Intent(main_activity, AddCountryVisited.class);
        	main_activity.startActivityForResult(intent,0);
        	return true;
        case R.id.by_country:
        	edit.putString("SortOrder", "Country");
        	edit.commit();
        	sortBy("Country");        	
        	
        	return true;
        case R.id.by_year:
        	
        	edit.putString("SortOrder", "Year");
        	edit.commit();
        	sortBy("Year");
        	return true;
        case R.id.settings:
    		/* Start new Activity CountryVisited */
    		Intent prefintent = new Intent(main_activity, SetPrefrencesCountryVisited.class);
    		//main_activity.startActivity(prefintent);
        	startActivity(prefintent);
    		
        	return true;
        default:
            return super.onOptionsItemSelected(item);
        } 
    }

    class MyAdapter extends ArrayAdapter<Object> {
    	
    	public MyAdapter(Context context, int textViewResourceId) {
    		super(context,textViewResourceId);
    	}
    	
    	@Override   // Called when updating the ListView
    	public TextView getView(int position, View convertView, ViewGroup parent) {
    		
		   	/* Reuse super handling ==> A TextView from R.layout.list_item */
		   	TextView tv = (TextView) super.getView(position,convertView,parent); 
		   	/* Find corresponding entry */
		   	Object obj = getItem(position);	
		    	
	    	if(obj instanceof String){
				tv.setText((String)obj);
			}
			if(obj instanceof CountryVisited){
		   		tv.setText((String)obj.toString());
		   		setPreferences(tv);
		    }
	    		
		   	return tv;	
//    		return (TextView) convertView;
    	}
    }
       
    @Override  
    public void onCreateContextMenu(ContextMenu menu, View v,ContextMenuInfo menuInfo) {  
    	super.onCreateContextMenu(menu, v, menuInfo);  
    	if (v.getId()==R.id.countryList) {
    		AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo)menuInfo;
    		menu.setHeaderTitle(countryVisits.get(info.position).toString());
    		menu.add(0, 0, 0, "Update");
    		menu.add(0, 1, 1, "Delete");
	    }
    }
    
    @Override
    public boolean onContextItemSelected(MenuItem item) {
      AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo)item.getMenuInfo();
      
      if (item.getItemId() == 0) { //update
			/* Start new Activity CountryVisited */
    	  updateFlag = true;
    	  Intent intent = new Intent(main_activity, AddCountryVisited.class);
    	  main_activity.startActivityForResult(intent,info.position);

      }
      if (item.getItemId() == 1) { //delete
    	  CountryVisited countryVisited = countryVisits.get(info.position);
    	  datasource.deleteCountryVisited(countryVisited);
    	  adapter.remove(countryVisited);
      }
      return true;
    }
    /** Called when the activity receives a results. */
    @Override
    protected void onActivityResult(int requestCode,int resultCode, Intent result) {
    	if (resultCode == RESULT_OK) {
    		Bundle resultBundle = result.getBundleExtra("result");
    		datasource.open();
    		
    		if(!updateFlag){
    			if(requestCode == 0){
    				addVisitedCountry(resultBundle.getInt("year"), resultBundle.getString("country"));
    			}
    			else{
    				showToast("Error! RequestCode = "+requestCode);
    			}
    		}
    		else{
    			updateVisitedCountry(resultBundle.getInt("year"), resultBundle.getString("country"), requestCode);
    			updateFlag = false;
    		}
    	}
    }
    
    /* Diagnostics while developing */
    private void showToast(String msg) {
    	Toast.makeText(this,msg,Toast.LENGTH_SHORT).show();
    }
}